#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Andrzej Rutkowski (andrzej.rutkowski+code (at) gmail.com)
#
# Tag Version 0.1 (alpha)
# This program can be distributed under the terms of the GNU GPL.
# See the file COPYING.
#

import sys
import shutil
import os
import getopt

from tagutil import TagSystem

def tagOpOnFile(path, op, tagLabel):
	dir = os.path.isdir(path)
	if not dir or not recursiveOpt:
		op(path, tagLabel)
	if dir and recursiveOpt:
		for f in os.listdir(path):
			tagOpOnFile(path+'/'+f, op, tagLabel)

try:
	args, files = getopt.gnu_getopt(sys.argv[1:], 'crt:d:Uu:l:L:m:', 
		['cloud', 'recursive', 'tag=', 'untag=', 'delete-tag=', 'list=', 
			'list-print0=', 'move=', 'copy=',
		]
	);
except getopt.GetoptError, e:
	print e
	exit(-1)

if len(args) == 0:
	execname = os.path.basename(sys.argv[0])
	if execname == "tagls":
		if len(files) < 1:
			args = [('-c', '')]
		else:
			args = [('-l', files[0])]
			files = files[1:]
	else:
		if len(files) < 1:
			exit(0)
		args = [('-t', files[0])]
		files = files[1:]

files = map(os.path.abspath, files)

recursiveOpt = False

tagSys = TagSystem()

for arg in args:
	if arg[0] in ('-r', '--recursive'):
		recursiveOpt = True
	elif arg[0] in ('-t', '--tag'):
		tagLabel = arg[1]
		if tagLabel == ".":
			tagLabel = tagSys.getLastTag()
		for path in files:
			tagOpOnFile(path, tagSys.tagFile, tagLabel)
		tagSys.setLastTag(tagLabel)
	elif arg[0] in ('-u', '--untag'):
		for path in files:
			tagOpOnFile(path, tagSys.untagFile, arg[1])
	elif arg[0] in ('-U',):
		for path in files:
			tagOpOnFile(path, tagSys.untagFile, '*')
	elif arg[0] in ('-d', '--delete-tag'):
		tagSys.untagAllFiles(arg[1])
	elif arg[0] in ('-l', '-L', '--list', '--list-print0'):
		tags = arg[1].split(',')
		if len(tags) == 1 and tags[0] == '':
			continue
		filesList = tagSys.getFilesByTags(tags);
		if arg[0] in ('-l', '--list'):
			cwd = os.getcwd()
			for path in sorted(filesList):
				if len(cwd) < len(path) and cwd == path[:len(cwd)]:
					print path[len(cwd)+1:]
				else:
					print path
		else:
			for path in sorted(filesList):
				sys.stdout.write(path)
				sys.stdout.write("\0")
	elif arg[0] in ('-c', '--cloud'):
		if len(files) == 0:
			cloud = tagSys.getTags()
		else:
			cloud = set()
			for path in files:
				cloud.update(tagSys.getTagsByFile(path))

		if len(cloud) > 0:
			for tag in cloud:
				print tag,
			print
				
	elif arg[0] in ('-m', '--move'):
		if len(files) > 0:
			tagSys.mvFilesByTag(arg[1], files[0])
		else:
			pass
			#print 'warning: move command needs destination'
	elif arg[0] in ('--copy',):
		if len(files) > 0:
			tagSys.copyFilesByTag(arg[1], files[0])
		
tagSys.close()
